//
//  SectionViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/27.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "SectionViewController.h"
#import "NewsDetailSectionModel.h"
#import "SectionCell.h"
#import "NetworkingTool.h"
#import "NewsListModel.h"
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "NewsDetailViewController.h"
#import "SQLiteManager.h"

@interface SectionViewController () 
/** story模型数组 */
@property (nonatomic, strong) NSMutableArray *stories;

/** 加载更多的时间戳数组 */
@property (nonatomic, strong) NSMutableArray *timestamps;

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;

/** 重新加载按钮 */
@property (nonatomic, weak) UIButton *reloadBtn;
@end

@implementation SectionViewController

static NSString *sectionReuseID = @"sectionCell";

#pragma mark - 懒加载
- (UIButton *)reloadBtn{
    if (!_reloadBtn) {
        UIButton *reloadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        reloadBtn.titleLabel.numberOfLines = 0;
        reloadBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        reloadBtn.hidden = YES;
        [reloadBtn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [reloadBtn setTitle:@"加载数据失败，点击重新加载" forState:(UIControlStateNormal)];
        [reloadBtn addTarget:self action:@selector(loadData) forControlEvents:(UIControlEventTouchUpInside)];
        [self.view addSubview:reloadBtn];
        _reloadBtn = reloadBtn;
    }
    return _reloadBtn;
}

- (NSMutableArray *)stories{
    if (!_stories) {
        _stories = [NSMutableArray array];
    }
    return _stories;
}

- (NSMutableArray *)timestamps{
    if (!_timestamps) {
        _timestamps = [NSMutableArray array];
    }
    return _timestamps;
}

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navBarView.title = self.section.name;
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SectionCell class]) bundle:nil] forCellReuseIdentifier:sectionReuseID];
    
    [self loadData];
    
    [self setupRefresh];
}

// 设置刷新控件
- (void)setupRefresh{
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreLists)];
    self.tableView.mj_footer.hidden = YES;
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.reloadBtn.frame = CGRectMake(20, (self.tableView.height - 60) * 0.5, self.tableView.width - 40, 60);
}

- (void)loadData{
    [self.stories removeAllObjects];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://news-at.zhihu.com/api/3/section/%d", self.section.ID];
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:urlStr parameters:nil finishedBlock:^(id responseObj, NSError *error) {
        if (error) {
            self.tableView.hidden = YES;
            self.reloadBtn.hidden = NO;
            return;
        }
        self.tableView.hidden = NO;
        [self.reloadBtn removeFromSuperview];
        
        [self.timestamps addObject:responseObj[@"timestamp"]];
        NSArray *stories = [NewsListModel mj_objectArrayWithKeyValuesArray:responseObj[@"stories"]];
        [self.stories addObjectsFromArray:stories];
        [self.tableView reloadData];
        self.tableView.mj_footer.hidden = NO;
        
       [SQLiteManager cacheStoryLists:responseObj[@"stories"] date:nil isTop:NO isLatest:NO isMore:NO];
    }];
}

// 加载更多数据
- (void)loadMoreLists{
    NSString *timeStamp = [NSString stringWithFormat:@"%@", self.timestamps.lastObject];
    NSString *urlStr = [NSString stringWithFormat:@"http://news-at.zhihu.com/api/3/section/%d/before/%@", self.section.ID, timeStamp];
    
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:urlStr parameters:nil finishedBlock:^(id responseObj, NSError *error) {
        if (error) return;
        
        
        NSArray *stories = [NewsListModel mj_objectArrayWithKeyValuesArray:responseObj[@"stories"]];
        [self.stories addObjectsFromArray:stories];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        
        [SQLiteManager cacheStoryLists:responseObj[@"stories"] date:nil isTop:NO isLatest:NO isMore:NO];
        
        if (!responseObj[@"timestamp"]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            [UIView animateWithDuration:1 animations:^{
                self.tableView.mj_footer.alpha = 0;
            } completion:^(BOOL finished) {
                self.tableView.mj_footer.hidden = YES;
            }];
            return;
        }
        [self.timestamps addObject:responseObj[@"timestamp"]];
    }];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.stories.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionCell *cell = [tableView dequeueReusableCellWithIdentifier:sectionReuseID];
    
    NewsListModel *model = self.stories[indexPath.row];
    model.alreadyRead = [SQLiteManager queryIsReadWithStoryID:model.ID];
    cell.model = model;
    
    // 切换皮肤
    if ([self.currentSkinModel isEqualToString:JKNightSkinModelValue]) {
        [cell changeToNightSkin];
        
    }else{
        [cell changeToDaySkin];
    }
    
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsListModel *model = self.stories[indexPath.row];
    NewsDetailViewController *detailVc = [[NewsDetailViewController alloc] init];
    detailVc.storyID = model.ID;
    detailVc.themeStories = self.stories;
    detailVc.indexPath = indexPath;
    [self.navigationController pushViewController:detailVc animated:YES];
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    self.currentSkinModel = currentSkinModel;
    
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        self.view.backgroundColor = JKNightSkinColor;
        [self.navBarView changeToNightSkin];
        
    }else{ // 日间模式
        self.view.backgroundColor = JKGlobalBgColor;
        [self.navBarView changeToDaySkin];
    }
    
    [self.tableView reloadData];
}
@end
